package com.lagou.client;

import com.lagou.pojo.RpcRequest;
import com.lagou.utils.RequestMetrics;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.net.InetSocketAddress;
import java.util.concurrent.Callable;

public class UserClientHandler extends ChannelInboundHandlerAdapter implements Callable {

    private ChannelHandlerContext context;
    private String result;
    private RpcRequest para;

    private RpcClient client;

    public UserClientHandler(RpcClient client) {
        this.client = client;
    }

    public void channelActive(ChannelHandlerContext ctx) {
        context = ctx;
        InetSocketAddress ipSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        int port = ipSocket.getPort();
        System.out.println("服务端建立连接port==========" +port);
    }

    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress ipSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        int port = ipSocket.getPort();
        System.out.println("服务端关闭连接port==========" +port);
        client.removeService();
        super.channelInactive(ctx);
    }

    /**
     * 收到服务端数据，唤醒等待线程
     */

    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) {
        String[] res = msg.toString().split(",");
        RequestMetrics.calculate(res[1]);
        result = res[0];
        notify();
    }

    /**
     * 写出数据，开始等待唤醒
     */

    public synchronized Object call() throws InterruptedException {
        client.setStart(para.getRequestId());
        context.writeAndFlush(para);
        wait();
        return result;
    }

    /*
     设置参数
     */
    void setPara(RpcRequest para) {
        this.para = para;
    }



}
